using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Random = System.Random;

public class BuildAb
{
    private const string PrefabDir = "Assets/Opsive/OmniAnimation";
    [MenuItem("OneKey/BuildAB")]
    static void BuildAB()
    {
        var guids =  AssetDatabase.FindAssets("t:prefab", new[] { PrefabDir });

        var buildList = new List<AssetBundleBuild>();
        foreach (var guid in guids)
        {
            var assetPath = AssetDatabase.GUIDToAssetPath(guid);
            var abBuild = new AssetBundleBuild()
            {
                assetBundleName = Path.GetFileNameWithoutExtension(assetPath) + ".bundle",
                assetNames = new string[1]{assetPath}
            };
            buildList.Add(abBuild);
        }

        var srcAbDir = Path.GetDirectoryName(Application.dataPath) + "/Output/Ab";
        Directory.CreateDirectory(srcAbDir);
        
        var option = BuildAssetBundleOptions.ChunkBasedCompression;
        var manifest = BuildPipeline.BuildAssetBundles(srcAbDir, buildList.ToArray(), option, EditorUserBuildSettings.activeBuildTarget);

        Directory.CreateDirectory(Application.streamingAssetsPath);
        CopyFilesWithRandomData(srcAbDir, Application.streamingAssetsPath);
    }
    
    static void CopyFilesWithRandomData(string sourceDir, string targetDir)
    {
        // 检查源文件夹是否存在
        if (!Directory.Exists(sourceDir))
        {
            Debug.LogError($"源文件夹 {sourceDir} 不存在。");
            return;
        }

        Directory.CreateDirectory(targetDir);

        // 获取源文件夹中的所有文件
        string[] files = Directory.GetFiles(sourceDir);

        // 创建一个随机数生成器
        Random random = new Random();

        foreach (string file in files)
        {
            try
            {
                // 获取文件名和扩展名
                string fileName = Path.GetFileName(file);
                string fileExtension = Path.GetExtension(file);

                // 构建目标文件的完整路径
                string destFile = Path.Combine(targetDir, fileName);

                // 如果文件以 .bundle 结尾，则处理
                if (fileExtension.ToLower() == ".bundle")
                {
                    // 读取源文件的内容
                    byte[] fileBytes = File.ReadAllBytes(file);

                    // 在文件头部插入随机长度的字节
                    var randomLength = TestLoadAb.MapFileNameToInt(fileName);
                    byte[] randomBytes = new byte[randomLength];
                    random.NextBytes(randomBytes);

                    // 合并随机字节和原文件内容
                    byte[] newFileBytes = new byte[randomBytes.Length + fileBytes.Length];
                    Array.Copy(randomBytes, 0, newFileBytes, 0, randomBytes.Length);
                    Array.Copy(fileBytes, 0, newFileBytes, randomBytes.Length, fileBytes.Length);

                    // 写入目标文件
                    File.WriteAllBytes(destFile, newFileBytes);
                }
                else
                {
                    // 普通拷贝文件
                    File.Copy(file, destFile, true);
                }

                Console.WriteLine($"文件 {fileName} 拷贝完成。");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"拷贝文件 {file} 时发生错误：{ex.Message}");
            }
        }
    }
    
    
    
}
